import cgi
import csv
import experiment

import os
from google.appengine.ext.webapp import template

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write('<html><body>')

        # Write the submission form and the footer of the page
        self.response.out.write("""
                        <form action="/upload" method="post" enctype="multipart/form-data">
                    <label>File: </label><input name="file" type="file"><br />
                    <input type="submit">
                </form>
            </body>
          </html>""")

class UploadData(webapp.RequestHandler):    
    def validate_upload_file(self):
        if 'file' not in self.request.POST:
            self.error(400)
            self.response.out.write("file not specified!")
            return False
        
        if (self.request.POST.get('file', None) is None or 
           not self.request.POST.get('file', None).filename):
            self.error(400)
            self.response.out.write("file not specified!")
            return False
           
    def post(self):
        # Check to see if the uploaded file is valid
        if (self.validate_upload_file() == False):
            return
        
        l = experiment.Loader(self.request.POST.get('file').file,5)
        l.load()
        template_values = {
            'experiments': l.experiments,
            'experiment_number': 1
            }

        path = os.path.join(os.path.dirname(__file__), 'templates/experiment.html')
        self.response.out.write(template.render(path, template_values))
        
class TestJS(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'templates/jstest.html')
        self.response.out.write(template.render(path, {}))


class TestJS2(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'templates/jstest2.html')
        self.response.out.write(template.render(path, {}))
        
application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/upload', UploadData),
                                      ('/testjs', TestJS),
                                      ('/testjs2', TestJS2)],
                                      debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()